package com.rankeiot.platform.controller;


import com.rankeiot.core.Current;
import com.rankeiot.core.anno.Auth;
import com.rankeiot.core.anno.DataScope;

import com.rankeiot.core.data.response.PageResp;
import com.rankeiot.core.data.response.Resp;
import com.rankeiot.core.inner.argumet.QueryPage;
import com.rankeiot.core.util.CollectionUtil;
import com.rankeiot.core.util.StringUtil;
import com.rankeiot.platform.PlatformMenu;
import com.rankeiot.platform.domain.User;
import com.rankeiot.platform.domain.UserRole;
import com.rankeiot.platform.service.RoleService;
import com.rankeiot.platform.util.PasswordUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.sagacity.sqltoy.dao.SqlToyLazyDao;
import org.sagacity.sqltoy.model.Page;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import static com.rankeiot.core.util.LocaleUtil.t;
/**
 * 用户
 *
 * @author desire
 */
@Tag(name="用户管理")
@RestController
@RequestMapping("user")
@RequiredArgsConstructor
public class UserController {

    final SqlToyLazyDao dao;
    final RoleService roleService;

    /**
     * 新增用户
     *
     * @param user  用户信息
     */
    @Operation(summary = "新增用户")
    @Auth(PlatformMenu.USER_ADD)
    @PostMapping("add")
    @Transactional
    public Resp add(@RequestBody(required = true) User user) {
        //@RequestParam(required = true) List<String> roles
        String password = user.getPassword();
        boolean newPass=false;
        if (StringUtil.isEmpty(password)) {
            newPass=true;
            password = PasswordUtil.generatePassword(8);// "123456";
        }
        user.setPassword(StringUtil.md5Hex(user.getUsername() + "$" + password));
        try {
            dao.save(user);
            List<UserRole> addUserRoles = CollectionUtil.map(user.getRoles(), role -> new UserRole(user.getUsername(), role));
            dao.saveAll(addUserRoles);
        } catch (Exception e) {
            String msg = e.getMessage();
            //唯一冲突
            String duplicate = "idx_username";
            if (msg.indexOf(duplicate) > 0) {
                Resp.fail(t("已存在同名用户","the same named user already exists"));
            }
            e.printStackTrace();
            Resp.fail(e.getMessage());
        }
        if(newPass){
            return Resp.of(password);
        }
        return Resp.ok();
    }

    /**
     * 删除用户
     *
     * @param users 用户列表，仅仅需要username就可以|[{username:"test"}]
     * @apiNote 删除传入用户列表
     */
    @Auth(PlatformMenu.USER_DELETE)
    @PostMapping("delete")
    @Transactional
    public Resp delete(@RequestBody List<User> users) {
        dao.deleteAll(users);
        //级联删除角色
        dao.executeSql("delete from t_user_role where user_name in (:users)", CollectionUtil.asMap("users", CollectionUtil.map(users,User::getUsername)));
        return Resp.ok();
    }

    /**
     * 更新用户信息
     *
     * @param user  用户信息
     */
    @Auth(PlatformMenu.USER_EDIT)
    @PostMapping("save")
    public Resp save(@RequestBody User user) {
        dao.update(user);
        //更新角色
        roleService.updateRolesOf(user.getUsername(), user.getRoles());
        //清除缓存的登录信息
       // Current.invalidateUser(user.getUsername());
        Current.invalidateAllUser();
        return Resp.ok();
    }

    @Operation(summary = "获取用户")
    @Auth(PlatformMenu.USER)
    @GetMapping("detail")
    public Resp<User> detail(User query) {
        User user = dao.load(query);
        if (user != null) {
            user.setRoles(roleService.getRoleSetOfUser(user.getUsername()));
        }
        return Resp.of(user);
    }

    @Operation(summary = "获取用户列表")
    @Auth(PlatformMenu.USER)
    @PostMapping("list")
    @DataScope(branch = "branch_sn")
    public PageResp<User> list(QueryPage query) {
        //@RequestBody User query,
//        QueryExecutor q = new ScopeExecutor("user_list", query)
//                //通过branch_sn过滤部门
//                .withBranch("branch_sn")
//                .executor();
        Page result = dao.findPageBySql(query.page(), "user_list", query.getParams(),User.class);

        return PageResp.of(result);
    }

    @Auth(PlatformMenu.USER)
    @PostMapping("alterPassword")
    public Resp alterPassword(String username,String password) {
        User user=new User();
        user.setUsername(username);
        user.setPassword(password);

        if (StringUtil.isEmpty(user.getUsername())||StringUtil.isEmpty(user.getPassword())) {
            Resp.fail(t("用户名或密码不能为空","username or password cannot be empty"));
        }
        //检测弱密码
        PasswordUtil.checkWeakPassword(user.getPassword());

        dao.executeSql("update t_user set password=md5(concat(username,'$',:password)),update_time=now() where username=:username", user);
        //清除已缓存用户信息，相当于踢出用户
        //Current.invalidateAllUser();//invalidateUser(user.getUsername());
        return Resp.ok();
    }

    @Auth(PlatformMenu.USER)
    @PostMapping("switchStatus")
    public Resp switchStatus(@RequestBody User user) {
        if (StringUtil.isEmpty(user.getUsername())) {
           Resp.fail(t("用户名不能为空","the username cannot be empty"));
        }
        if(user.getUsername().equals(Current.user().getUsername())){
            Resp.fail(t("不能禁用自己","cannot disable yourself"));
        }
        dao.executeSql("update t_user set enable=:enable where username=:username", user);
        if(!user.getEnable()){
            //清除已缓存用户信息，相当于踢出用户
           // Current.invalidateUser(user.getUsername());
            Current.invalidateAllUser();
        }
        return Resp.ok();
    }
}
